<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>角色管理</title>
</head>
<body>
<div class="layui-container">
	<div class="layui-form"
		lay-filter="add-role">
		<div style="padding-bottom: 10px;">
			<div class="layui-input-inline">
					<input type="text" id="roleName" name="roleName" placeholder="请输入角色名称"
						autocomplete="off" class="layui-input" lay-verify="roleName">
			</div>
          <button class="layui-btn" lay-submit lay-filter="*" data-type="add">添加</button>
        </div>
	</div>
	<table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
	<input type="hidden" id="selectedRoleId"/>
</div>
	<script type="text/javascript">
		var table = layui.table;
		var form = layui.form;
		form.verify({
			roleName: function(value, item){ //value：表单的值、item：表单的DOM对象
		    if(value.trim() == ''){
		      return '请输入角色名称';
		    }
		  }
		});  
		form.on('submit(*)', function(data){
		  console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
		  console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
		  console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
		  
		  $.ajax({
			  url:window.basePath+ '/sys/addRole',
				headers: {"token" : window.token},
				method: "post",
			  dataType:'json',
			  data:data.field,
			  success:function(data){
				  if(data){
					  layer.msg(data.message);
				  }
				  tableIns.reload();
			  }
		  });
		  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
		});
		var roleName = $("#roleName").val();	
		var tableIns = table.render({
			elem : '#roleTable',
			url :window.basePath+  '/sys/findRoleByPage',
			headers: {"token" : window.token},
			method: "post",
			where:{roleName:roleName},
			height : 'full-150',
			limit:10,
			cols : [ [{
				width : 80,
				title : '序号',
				type:'numbers'
			} , {
				field : 'roleName',
				width : 200,
				align : 'center',
				title : '角色名称'
			}, {
				fixed : 'right',
				width : 200,
				align : 'center',
				toolbar : '#barDemo'
			} ] ],
			text : {
				none : '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
			},
			page : true,
			done: function(res, curr, count){
			}
		});

		//监听表格复选框选择
		table.on('checkbox(roleTable)', function(obj) {
			console.log(obj)
		});
		table.on('tool(roleTable)', function(obj) {
			var data = obj.data; //获得当前行数据
			var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
			var tr = obj.tr; //获得当前行 tr 的DOM对象
			var id = obj.data.id;
			if (layEvent === 'del') {
				layer.confirm('您确定要删除吗？', function(index) {
					obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
					layer.close(index);
					//向服务端发送删除指令
					 $.ajax({
						  url:window.basePath+ '/sys/deleteRoleById',
							headers: {"token" : window.token},
							method: "post",
						  dataType:'json',
						  data:{
							  roleId:data.id
						  },
						  success:function(data){
							  if(data){
								  layer.msg(data.message);
							  }
							  tableIns.reload();
						  }
					  });
				});
			}else if (layEvent === 'user') {
				openUsersView(id);
			}
			else if (layEvent === 'resource') {
				openMenusView(id);
			}
		})
		
		function getCheckData(){ //获取选中数据
	      var checkStatus = table.checkStatus('employeesTable')
	      ,data = checkStatus.data;
	      return data;
	    }
    	//绑定用户到角色
    	function bindEmployeeRole(){
    		var data = getCheckData();
    	}
    	//打开用户绑定弹出页面
    	function openUsersView(id){
    		$("#selectedRoleId").val(id);
			layer.open({
			  type:2,
			  title:'员工绑定/解绑',
			  area: ['920px', '560px'],
			  content:window.basePath+ "/sys/roleUserManagement",
			  btn: ['关闭'],
		      btnAlign: 'c',
		      id:'roleUserView',
		      btn1: function(){
		      	layer.closeAll();
		      }
			});
		}
    	//打开菜单管理弹出页面
    	function openMenusView(id){
    		$("#selectedRoleId").val(id);
			layer.open({
			  type:2,
			  title:'资源管理',
			  area: ['890px', '560px'],
			  content:window.basePath+ "/sys/roleSource",
			  btn: ['保存','取消'],
		      btnAlign: 'c',
		      id:'roleMenuView',
		      btn1: function(){
		    	//保存角色绑定菜单数据
		      	saveRoleSource();
		      },
		      btn2:function(){
		    	  layer.closeAll();
		      }
			});
		}
    	
    	//保存角色绑定菜单数据
    	function saveRoleSource(){
    		var roleId = $("#selectedRoleId").val();
    		var bindIds="";
    		var unbindIds="";
    		var divObj = window.frames[0].document.getElementById("menusDiv");
    		var checkboxArr = $(divObj).find("input[lay-filter='selectSubMenu']");
    		for(var i=0;i<checkboxArr.length;i++){
    			var obj = checkboxArr[i];
    			var isChecked = $(obj).prop("checked");
    			var objVal = $(obj).val();
    			if(isChecked == true){
    				bindIds=bindIds+objVal+",";
    			}else{
    				unbindIds = unbindIds+objVal+",";
    			}
    		}
    		$.ajax({
    			url: window.basePath+ "/sys/saveRoleMenuBindInfo",
    			type: "POST",
					headers: {"token" : window.token},
    			dataType: 'json',
    			data:{roleId:roleId,bindIds:bindIds,unbindIds:unbindIds},
    			success: function(data) {
    				if(data.success){
    					layer.alert("绑定成功！",function(index){
    						layer.closeAll();
   						});   
    				}
    			},
    			error:function(){
    				layer.alert("操作失败");
    			}
    		});
    	}
	</script>
	<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="user">绑定用户</a>
  <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="resource">关联资源</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</body>

</html>